package com.izhangqian.signproject.viewmodel;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.izhangqian.pluginapk.PluginEntry;
import com.izhangqian.signproject.beans.ApkConfig;
import com.izhangqian.signproject.beans.PluginBean;
import com.izhangqian.signproject.plugin.PluginApk;
import com.izhangqian.signproject.utils.LogUtils;
import com.izhangqian.signproject.utils.PluginManager;
import com.izhangqian.signproject.webrequest.api.ControlGetRep;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Scheduler;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PluginsViewModel extends AndroidViewModel {

    public MutableLiveData<List<PluginBean>> pluginBeans = new MutableLiveData<>();
    public PluginsViewModel(@NonNull Application application) {
        super(application);
    }

    public void getPlugins(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<PluginApk> apks = PluginManager.getInstance(context).getApks();
                if (apks == null || apks.size() == 0) {
                    pluginBeans.postValue(null);
                    return;
                }

                List<PluginBean> list = new ArrayList<>();
                for (PluginApk pluginApk : apks) {
                    PluginEntry entry = pluginApk.getEntry();
                    PluginBean bean = new PluginBean();
                    if (entry != null) {
                        bean.name = entry.getName();
                    }
                    list.add(bean);;
                }
                pluginBeans.postValue(list);
            }
        }).start();
    }

    public void getConfig() {
        ControlGetRep.INSTANCE.getNewApkConfig().subscribeOn(Schedulers.io()).subscribe(new Consumer<ApkConfig>() {
            @Override
            public void accept(ApkConfig apkConfig) throws Exception {
                LogUtils.i("vIEWMOdel", "config: " + apkConfig.getApkMD5());
            }
        });
    }
}
